const api = require("./api.js");
module.exports = {
  // 登录
  async login(user) {
    const loginRes = await api.MiniLogin({"PhoneNumber": user.phoneNumber})
    user.bindBusinessId = loginRes.data.businessId
    if(loginRes.success && user.remeber) {
      wx.setStorage({
        key: "user", // 缓存数据的键名
        data: user, // 要缓存的数据
        success(res) {
          console.log("数据保存成功", res);
        },
        fail(err) {
          console.error("数据保存失败", err);
        }
      })
    }
    return loginRes
  },

  // 通知服务器已连接电池
  async sendConnectInfoToServer(deviceId) {
    try {
      // 1. 从缓存中获取 user 数据（使用同步或封装成 Promise）
      const res = await new Promise((resolve, reject) => {
        wx.getStorage({
          key: "user",
          success: resolve,
          fail: reject
        });
      });
  
      const phoneNumber = res.data.phoneNumber;
  
      if (!phoneNumber) {
        throw new Error("手机号不存在");
      }
  
      // 2. 调用接口发送数据
      const result = await api.MiniPostConnection({
        PhoneNumber: phoneNumber,
        BatteryMAC: deviceId
      });
  
      console.log("发送成功", result);
      return result;
  
    } catch (err) {
      console.error("发送失败", err);
      throw err; // 或者根据需要处理错误
    }
  },

  // 获取指令
  async getCommand(deviceId) {
    return await api.MiniGetAllOrderCode({"BatteryMAC": deviceId})
  },

  // 发送指令执行的结果
  async sendCommandExecuteResult(deviceId, batteryInfo) {
    return await api.DealBatteryData({"BatteryMAC": deviceId, "BatteryData": batteryInfo})
  },

  // 查看电池信息
  async getBatteryInfo(device) {
    let result = await api.MiniGetBatteryDetails({"BatteryMAC": device.deviceId, "BatteryName": device.name})
    // 开始整理电池信息格式


    // 先复制data
    let dataCopy = JSON.parse(JSON.stringify(result.data));
    // 新batteryInfo的最外层只放基础信息
    const updatedDevice = {
      deviceId: device.deviceId,
      name: device.name,
      sn: dataCopy.batterySN,
      softwareVersion: dataCopy.softwareVersion,
      hardwareVersion: dataCopy.hardwareVersion,
      power: Math.floor(dataCopy.soc/2),
      health: dataCopy.soh,
      parameter: [
        { key: "总电压", value: dataCopy.voltage + "V", icon: "V"},
        { key: "总电流", value: dataCopy.current + "A", icon: "A"},
        { key: "总循环", value: dataCopy.cycles + "次", icon: ""},
        { key: "最大总电压", value: dataCopy.maxAllVoltage + "V", icon: "V"},
        { key: "最高电压", value: dataCopy.maxVoltage + "V", icon: "V"},
        { key: "最高电压节数", value: dataCopy.maxVoltageNum + "节", icon: ""},
        { key: "最低电压", value: dataCopy.minVoltage + "V", icon: "V"},
        { key: "最低电压节数", value: dataCopy.minVoltageNum + "节", icon: ""},
        { key: "最大充电电流", value: dataCopy.maxChargingCurrent + "A", icon: "A"},
        { key: "最大放电电流", value: dataCopy.maxDischargingCurrent + "A", icon: "A"},
        { key: "最高温度", value: dataCopy.maxTemperature + "℃", icon: "℃"},
        { key: "最低温度", value: dataCopy.minTemperature + "℃", icon: ""},
        { key: "总容量", value: dataCopy.fullCapacity + "AH", icon: ""},
        { key: "剩余容量", value: dataCopy.remainCapacity + "AH", icon: ""},
        { key: "最大未充电时间", value: dataCopy.maxNoChargingTime + "", icon: ""},
        { key: "最大未放电时间", value: dataCopy.maxNoDischargingTime + "", icon: ""},
      ],
      status: {
        preDischargeMosStatus: dataCopy.preDischargeMosStatus,
        equilibriumStatus: dataCopy.equilibriumStatus,
        chargingMosStatus: dataCopy.chargingMosStatus,
        disChargingStatus: dataCopy.disChargingStatus,
      },
      mos: {
        m: dataCopy.tMos,
        t: [dataCopy.t0, dataCopy.t1, dataCopy.t2, dataCopy.t3]
      },
      log: {
        protect: dataCopy.protectingList,
        waring: dataCopy.warningList,
      },
      singleCellVoltageList: dataCopy.singleCellVoltageList
    };

    
    // 创建一个新的结果对象，避免循环引用
    return {
      ...result,
      data: updatedDevice
    };
  },

  // 获取质保列表
  async getWorkOrderList() {
    try {
      // 1. 从缓存中获取 user 数据（使用同步或封装成 Promise）
      const res = await new Promise((resolve, reject) => {
        wx.getStorage({
          key: "user",
          success: resolve,
          fail: reject
        });
      });
  
      const phoneNumber = res.data.phoneNumber;
  
      if (!phoneNumber) {
        throw new Error("手机号不存在");
      }
  
      // 2. 调用接口发送数据
      let result = await api.MiniGetMaintenanceList({
        PhoneNumber: phoneNumber
      });
      
      const newArray = result.data.map(item => {
        return {
          ...item,
          show: true
        }
      });
      result.data = newArray
      return result
  
    } catch (err) {
      console.error("发送失败", err);
      throw err; // 或者根据需要处理错误
    }
  },

  // 待激活电池信息获取
  async waitActive(deviceId) {
    let formData = {}
    formData.deviceId = deviceId
    formData.success = false
    const statusRes = await api.MiniGetBatteryActivity({BatteryMAC: deviceId})
    const dateRes = await api.MiniGetProductDate({BatteryMAC: deviceId})
    if (dateRes.success) {
      formData.success = true
      formData.activeDate = dateRes.data.activityTime
      formData.endTime = dateRes.data.endTime
    } else {
      formData.activeDate = '数据获取失败'
      formData.endTime = '数据获取失败'
    }
    formData.sn = ''
    formData.city = ''
    formData.address = ''
    formData.phoneNumber = wx.getStorageSync('user').phoneNumber

    return formData
  },

  // 激活电池
  async activeBattery(activeFormData) {
    return await api.MiniPostActivity({
      BatterySN: activeFormData.sn,
      BatteryMAC: activeFormData.deviceId,
      ActivityTime: activeFormData.activeDate,
      PhoneNumber: activeFormData.phoneNumber,
      Address: activeFormData.address,
      City: activeFormData.city,
    })
  },

  // 获取质保详情
  async getWorkOrderDetail(maintenanceNumber) {
    const result = await api.MiniGetMaintenanceInfo({MaintenanceNumber: maintenanceNumber})
    let dataCopy = JSON.parse(JSON.stringify(result.data));
    const updateData = {
      deviceId: dataCopy.batteryMAC,
      sn: dataCopy.batterySN,
      dealName: dataCopy.dealName,
      dealPhoneNumber: dataCopy.dealPhoneNumber,
      dealReason: dataCopy.dealReason,
      dealTime: dataCopy.dealTime,
      dealWay: dataCopy.dealWay,
      maintenanceBluetoothStatus: dataCopy.maintenanceBluetoothStatus,
      maintenanceChargingStatus: dataCopy.maintenanceChargingStatus,
      maintenanceDischargingStatus: dataCopy.maintenanceDischargingStatus,
      maintenanceNumber: dataCopy.maintenanceNumber,
      userImages: [
        {
          url: dataCopy.maintenancePhotoFirst,
          name: 1
        },
        {
          url: dataCopy.maintenancePhotoSecond,
          name: 2
        },
        {
          url: dataCopy.maintenancePhotoThird,
          name: 3
        }
      ],
      maintenanceProblem: dataCopy.maintenanceProblem,
      newDeviceId: dataCopy.newBatteryMAC,
      newBatterySN: dataCopy.newBatterySN,
      postTime: dataCopy.postTime,
    }

    return {
      ...result,
      data: updateData
    };
  },

  // 获取商户列表
  async getBusinessList() {
    try {
      // 1. 从缓存中获取 user 数据（使用同步或封装成 Promise）
      const res = await new Promise((resolve, reject) => {
        wx.getStorage({
          key: "user",
          success: resolve,
          fail: reject
        });
      });
  
      const phoneNumber = res.data.phoneNumber;
  
      if (!phoneNumber) {
        throw new Error("手机号不存在");
      }
  
      // 2. 调用接口发送数据
      let result = await api.MiniGetBusinessList({
        PhoneNumber: phoneNumber
      });
      
      return {
        ...result,
        data: result.businessList
      };
  
    } catch (err) {
      console.error("发送失败", err);
      throw err; // 或者根据需要处理错误
    }
  },

  // 绑定商户
  async bindBusiness(businessId) {
    try {
      // 1. 从缓存中获取 user 数据（使用同步或封装成 Promise）
      const res = await new Promise((resolve, reject) => {
        wx.getStorage({
          key: "user",
          success: resolve,
          fail: reject
        });
      });
  
      const phoneNumber = res.data.phoneNumber;
  
      if (!phoneNumber) {
        throw new Error("手机号不存在");
      }

      const bindRes = await api.MiniBindBusiness({ PhoneNumber: phoneNumber, BusinessId: businessId })

      if (bindRes.success) {
        let userData = wx.getStorageSync('user');
        userData.bindBusinessId = businessId;
        wx.setStorageSync('user', userData);
      }

      return bindRes
  
    } catch (err) {
      console.error("发送失败", err);
      throw err; // 或者根据需要处理错误
    }

  },

  // 查看电池列表
  async getBatteryList() {
    try {
      // 1. 从缓存中获取 user 数据（使用同步或封装成 Promise）
      const res = await new Promise((resolve, reject) => {
        wx.getStorage({
          key: "user",
          success: resolve,
          fail: reject
        });
      });
  
      const phoneNumber = res.data.phoneNumber;
  
      if (!phoneNumber) {
        throw new Error("手机号不存在");
      }
  
      const result = await api.MiniGetUserBattery({
        PhoneNumber: phoneNumber
      })

      return {
        ...result,
        data: result.all
      }
  
    } catch (err) {
      console.error("发送失败", err);
      throw err; // 或者根据需要处理错误
    }
  }
}